
package com.epam.android.training;

import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * File Selector Activity.
 * 
 * @author Natallia_Kukharchyk
 */
public class FileSelector extends ListActivity {

  private final String ROOT = "/";

  private final String UP = "../";

  private final String IMAGE_JPEG = "image/jpeg";

  private final String JPEG = "jpg";

  private final String URI_PREFIX = "file://";

  private List<String> item = null;

  private List<String> path = null;

  private FileSelectorDb db;

  private ListAdapter adapter;

  private Cursor c;

  private ArrayAdapter<String> modeAdapter;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    db = new FileSelectorDb(getApplicationContext());
    Button addButton = (Button) findViewById(R.id.btn_add);
    addButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        // set up dialog
        final Dialog dialog = new Dialog(FileSelector.this);
        dialog.setContentView(R.layout.dialog_layout);
        final ListView modeList = (ListView) dialog.findViewById(R.id.list_view);
        // preview img on long click
        modeList.setOnItemLongClickListener(new OnItemLongClickListener() {

          @Override
          public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            File file = new File(path.get(position));
            if (file.isDirectory() || !file.getName().endsWith(JPEG)) {
              return false;
            }
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(Uri.parse(URI_PREFIX + file.getAbsolutePath()), IMAGE_JPEG);
            startActivityForResult(i, 1);
            return true;
          }

        });
        modeList.setOnItemClickListener(new OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
            File file = new File(path.get(position));
            if (file.isDirectory()) {
              if (file.canRead()) {
                modeList.setAdapter(modeAdapter = getFileList(path.get(position)));
                modeAdapter.notifyDataSetChanged();
              } else {
                Toast toast = Toast.makeText(getApplicationContext(), getString(R.string.cannot_read),
                    Toast.LENGTH_SHORT);
                toast.show();
              }
            } else {
              db.insertFile(file.getAbsolutePath());
              c.requery();
              dialog.dismiss();
            }

          }
        });
        modeAdapter = getFileList(ROOT);
        modeAdapter.setNotifyOnChange(true);
        modeList.setAdapter(modeAdapter);

        dialog.setTitle(getString(R.string.dialog_title));
        dialog.setCancelable(true);
        Button button = (Button) dialog.findViewById(R.id.btn_cancel);
        button.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
            dialog.cancel();
          }
        });
        // now that the dialog is set up, it's time to show it
        dialog.show();
      }
    });

    c = new FileSelectorDb(getApplicationContext()).getFilesCursor();
    startManagingCursor(c);

    // using simple cursor adapter to map data to view
    adapter = new SimpleCursorAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, c, new String[] {
      FileSelectorOpenHelper.FILE_NAME
    }, new int[] {
      android.R.id.text1
    });

    setListAdapter(adapter);
  }

  private ArrayAdapter<String> getFileList(String dirPath) {
    item = new ArrayList<String>();
    path = new ArrayList<String>();
    File f = new File(dirPath);
    File[] files = f.listFiles();
    if (!dirPath.equals(ROOT)) {
      item.add(ROOT);
      path.add(ROOT);
      item.add(UP);
      path.add(f.getParent());
    }

    for (int i = 0; i < files.length; i++) {
      File file = files[i];
      path.add(file.getPath());
      if (file.isDirectory()) {
        item.add(file.getName() + "/");
      } else {
        item.add(file.getName());
      }
    }
    return new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, item);
  }
}
